package faceb.server.dao.impl;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.stereotype.Repository;

import faceb.server.dao.UserDao;
import faceb.server.model.User;
import faceb.server.util.MyBatisUtil;

@Repository("userDao")
public class UserDaoImpl implements UserDao {

	private SqlSessionFactory factory = MyBatisUtil.getsqlSessionFactory();

	public User getUserByEmail(String email) {
		SqlSession session = factory.openSession();
		User u = session.selectOne("UserMapper.queryUserByEmail", email);
		session.commit();
		session.close();
		return u;
	}

	public User login(String email, String password) {
		SqlSession session = factory.openSession();
		Map<String, String> params = new HashMap<String, String>();
		params.put("email", email);
		params.put("pass", password);
		User u = session.selectOne("UserMapper.login", params);
		session.close();
		return u;
	}

	public int register(User u) {
		SqlSession session = factory.openSession();
		int result = 0;
		try {
			boolean isEmailExist = isEmailExists(u.getU_email());
			if (isEmailExist) {
				result = 0;
			} else {
				result = session.insert("UserMapper.register", u);
				session.commit();
			}
		} catch (Exception e) {
			System.out.println(e.toString());
			result = 0;
		}
		session.close();
		return result;
	}

	public boolean isEmailExists(String email) {
		String result = null;
		SqlSession session = factory.openSession();
		result = session.selectOne("UserMapper.isEmailExists", email);
		session.close();
		if (result == null)
			return false;
		return true;
	}

	public User getUserById(String userid) {

		SqlSession session = factory.openSession();
		User u = session.selectOne("UserMapper.queryUserById", userid);
		session.commit();
		session.close();
		return u;
	}

	

	public int completeUser(User user) {
		SqlSession session = factory.openSession();
		int result = session.update("UserMapper.complete", user);
		session.commit();
		session.close();
		return result;
	}

	
	public static void main(String[] args) {}
}
